<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;
/**
 * @mixin think\Model
 */
class Category extends Model
{
    // 主键
    protected $pk = 'cid';
    // json字段
	protected $json = ['images'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;
	// 修改器：从images字段获取封面Cover字段
	public function setCoverAttr($value,$data) {
		if (isset($data['images']) && is_array($data['images'])) {
			return $data['images'][0] || null;
		}else{
			return null;
		}
	}
    public function getTreeData()
    {
        $all = $this->scope('normal')->select();
        $res = $this->tree($all, 0);
        return $res;
    }
    private function tree($list, $parent){
        $res = [];
        foreach ($list as $key => $value) {
            if($parent === $value['pid'])
            {
                $tmp = $value;
                $children = $this->tree($list, $value['cid']);
                if(sizeof($children) > 0){
                    $tmp['children'] = $children;
                }
                $res[] = $tmp;
            }
        }
        return $res;
    }
}
